package com.zx.web.servelt;

import com.alibaba.fastjson.JSON;
import com.zx.bean.User;
import com.zx.web.service.AdminUserService;
import com.zx.web.service.impl.AdminUserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.servelt
 * @Description:
 * @Date 2022/9/16 9:34
 */
@WebServlet("/adminuserservlet")
public class AdminUserServlet extends BaseServlet{

    AdminUserService adminUserService = new AdminUserServiceImpl();

    /**
     * 管理员登录
     * @param req
     * @param resp
     * @return
     */
    public String adminLogin(HttpServletRequest req, HttpServletResponse resp){
        //获取请求数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //查询
        User admin = adminUserService.findAdmin(username,password);
        // 存入Session域
        req.getSession().setAttribute("admin",admin);

        //跳转主页
        return "redirect:/admin/admin.jsp";
    }

    /**
     * 查询有效用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void getUserList(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //查询用户表
        List<User> userList =  adminUserService.findAllValid();
        //转化为json数据
        String list = JSON.toJSONString(userList);
        //传入前端
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(list);
    }

    /**
     * 删除用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void deleteUser(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        adminUserService.deleteUser(id);
    }

    /**
     * 搜索
     * @param req
     * @param resp
     * @throws IOException
     */
    public void searchUser(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String gender = req.getParameter("gender");

        List<User> userList = adminUserService.findUserList(username,gender);

        String s = JSON.toJSONString(userList);
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(s);
    }

    /**
     * 查询无效用户
     * @param req
     * @param resp
     * @throws IOException
     */
    public void getUserListInvalid(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //查询用户表
        List<User> userList =  adminUserService.findAllInValid();
        //转化为json数据
        String list = JSON.toJSONString(userList);
        //传入前端
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(list);
    }

}
